package com.viu.technology.chat.listener;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.viu.technology.dto.ChatMessage;
import com.viu.technology.service.message.MessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ChatDurableHandler implements ChannelAwareMessageListener {

    private static final Logger log = LoggerFactory.getLogger(ChatDurableHandler.class);

    @Autowired
    private MessageService messageService;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long startTime = System.currentTimeMillis();
        try {
            String body = new String(message.getBody());
            //log.info("Durable监听器接收到消息 : " + body);
            JSONObject imJson = JSONObject.parseObject(body);
            ChatMessage msg = JSONObject.parseObject(imJson.getString("data"), ChatMessage.class);
            boolean b=messageService.durableChatMessage(msg);
            if (b) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,true);
            }
        } catch (IOException e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,true);
        }
        log.info("耗时————————" + (System.currentTimeMillis() - startTime));
    }
}
